package wt.jly.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import wt.jly.domain.User;
import wt.jly.service.UserService;

import java.util.List;

/**
 * @author lanyangji
 * @date 2018/9/18 21:10
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

//        info.addStringPermission("product:add");

        // 动态授权
        Subject subject = SecurityUtils.getSubject();
        User dbUser = (User) subject.getPrincipal();
        List<String> permissions = userService.findPermissionsByUserId(dbUser.getId());

        if (!CollectionUtils.isEmpty(permissions)) {
            for (String permission : permissions) {
                if (!StringUtils.isEmpty(permission)) {
                    info.addStringPermission(permission);
                }
            }
        }

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 1. 获取用户输入的账户信息
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

//        String name = "lanyangji";
//        String password = "123";
//
//        if (!usernamePasswordToken.getUsername().equals(name)) {
//            return null;
//        }

//        User dbUser = new User();
//        dbUser.setUserName(name);
//        dbUser.setPassword(password);

        // 动态验证
        User dbUser = userService.findByUserName(usernamePasswordToken.getUsername());
        if (ObjectUtils.isEmpty(dbUser)) {
            return null;
        }

        return new SimpleAuthenticationInfo(dbUser, dbUser.getPassword(),"");
    }
}
